<?php


namespace App\Http\Services;


use App\AuthorizerInfo;
use App\AvailableUrl;
use App\Http\Controllers\Api\Admin\PlatformController;
use App\Http\Controllers\Api\WeChatThirdController;
use App\Orders;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class DomainManager
{
    /**
     * 获取请求的域名配置信息
     * @author cmj
     *
     * @param Request $request
     *
     * @return array
     */
    protected static function getConfig(Request $request)
    {
        if ($request->APPID){
            if (strtolower($request->APPID) == 'api' ){
                $fullUrl=$request->root();
//        $availableUrls=AvailableUrl::all();
//        $url=explode('.',$fullUrl)[0];
                $array=[
                    'http://',
                    'Http://',
                    'HTTP://',
                    'https://',
                    'Https://',
                    'HTTPS://'
                ];
                $domain     = str_replace($array,'',$fullUrl);
                $raw_data   = Redis::get($domain.'.config');
                if ($raw_data){
                    return ['success'=>true,'message'=>'success','data'=>json_decode($raw_data)];
                }
                $config=AvailableUrl::whereDomain($domain)->first();
                if ($config){
                    if ($config->expire_date){
                        $expire_date=strtotime($config->expire_date);
                        if ($expire_date){
                            if ($expire_date < time()){
                                return ['success'=>false,'message'=>'服务已过期','data'=>[]];
                            }
                        }
                    }
                    $raw_data=json_encode($config);
                    Redis::set($domain.'.config',$raw_data,'EX','3600');
                    return ['success'=>true,'message'=>'success','data'=>$config];
                } else {
                    return ['success'=>false,'message'=>'服务未被授权','data'=>$domain];
                }
            }
            else {
                $appid = strtolower($request->APPID);
                $raw_data   = Redis::get($appid.'.config');
                if ($raw_data){
                    return ['success'=>true,'message'=>'success','data'=>json_decode($raw_data)];
                }
                $config=AvailableUrl::whereMiniprogramAppid($appid)->first();
                if ($config){
                    if ($config->expire_date){
                        $expire_date=strtotime($config->expire_date);
                        if ($expire_date){
                            if ($expire_date < time()){
                                return ['success'=>false,'message'=>'服务已过期','data'=>[]];
                            }
                        }
                    }
                    $raw_data=json_encode($config);
                    Redis::set($appid.'.config',$raw_data,'EX','3600');
                    return ['success'=>true,'message'=>'success','data'=>$config];
                } else {
                    return ['success'=>false,'message'=>'服务未被授权','data'=>$appid];
                }
            }
        }

    }

    /**
     * @param $enterpriseId
     * @return AvailableUrl|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    protected static function getConfigByEnterpriseId($enterpriseId){
        $config=AvailableUrl::whereEnterpriseId($enterpriseId)->first();
        return $config ?? null;
    }

    /**
     * 获取请求域名
     * @param Request $request
     * @return mixed
     */
    public static function getDomain(Request $request){
        $fullUrl=$request->root();

        $array=[
            'http://',
            'Http://',
            'HTTP://',
            'https://',
            'Https://',
            'HTTPS://'
        ];
        $domain     = str_replace($array,'',$fullUrl);
        return $domain;
    }
    /**
     * 获取请求的域名所属企业id
     * @author cmj
     * @param Request $request
     * @return int
     */
    public static function getEnterpriseId(Request $request)
    {
        $data=self::getConfig($request) ?? 0;
        if (!$data)
            return 0;
        if ($data['success']){
            /** @var AvailableUrl $config */
            $config=$data['data'];
            return $config ? (int)$config->enterprise_id : 0;
        }
        return 0;
    }

    public static function getAppId(Request $request){
        $data=self::getConfig($request) ?? false;
        if (!$data)
            return '';
        if ($data['success']){
            $config=$data['data'];
            return $config ? $config->miniprogram_appid : '';
        }
        return '';
    }
    public static function getAppName($app_id){
        $temp_name  = Redis::get($app_id.'.name');
        if ($temp_name)
            return $temp_name;
        $platform   = Factory::openPlatform(WeChatThirdController::getPlatformConfig());
        $data       = $platform->getAuthorizer($app_id);
        if (!$data)
            return false;
        if (!isset($data['authorizer_info']))
            return false;
        if (!isset($data['authorizer_info']['nick_name']))
            return false;
        $name = $data['authorizer_info']['nick_name'];
        if (!$name){
            return false;
        }
        \Log::notice("Redis Cache AppID:$app_id => $name");
        Redis::set($app_id.'.name',$name);
        return $name;
    }


    /**
     * 获取微信支付配置信息
     * @param Request $request
     * @return array|null
     */
    public static function getPayConfig(Request $request){
        $data=self::getConfig($request) ?? false;
        if (!$data)
            return null;
        if ($data['success']){
            /** @var AvailableUrl $result */
            $result=$data['data'];
            $config = [
                // 必要配置
                'app_id'             => $result->miniprogram_appid,
                'mch_id'             => $result->wechatpay_mchid,
                'key'                => $result->wechatpay_key
            ];
            return $config;
        }
        return null;
    }

    /**
     * 获取退款配置
     * @param Orders $thisOrder
     * @return array|null
     */
    public static function getUnPayConfig(Orders $thisOrder){
        $result=self::getConfigByEnterpriseId($thisOrder->enterprise_id) ?? false;
        if (!$result)
            return null;
        /** @var AvailableUrl $result */
        $config = [
                // 必要配置
                'app_id'             => $result->miniprogram_appid,
                'mch_id'             => $result->wechatpay_mchid,
                'key'                => $result->wechatpay_key,
                'cert_path'          => storage_path() . '/app/cert/'.$result->wechatpay_certificate_cert_name.'.pem',
                'key_path'           => storage_path() . '/app/key/'.$result->wechatpay_certificate_key_name.'.pem',
            ];
        return $config;
    }

    /**
     * 获取企业付款到零钱配置（临时用）
     * @Author Jolly
     * @Param Orders $thisOrder
     * @return array|null
     */
    public static function getUnPayConfigByAppId($appId,$mchid){
        $availableInfo = AvailableUrl::whereMiniprogramAppid($appId)->whereWechatpayMchid($mchid)->first();
        $result=$availableInfo ?? false;
        if (!$result)
            return null;
        /** @var AvailableUrl $result */
        $config = [
            // 必要配置
            'app_id'             => $result->miniprogram_appid,
            'mch_id'             => $result->wechatpay_mchid,
            'key'                => $result->wechatpay_key,
            'cert_path'          => storage_path() . '/app/cert/'.$result->wechatpay_certificate_cert_name.'.pem',
            'key_path'           => storage_path() . '/app/key/'.$result->wechatpay_certificate_key_name.'.pem',
        ];
        return $config;
    }
}
